<?php
$sina = new sina ();
$sina->login2 ();
//$sina->getFollow();
//sleep(5);
$sina->comentFollow('tanzhiqian','上班了',2);
class sina {
    public $user = 'mailzsm@126.com';
    public $pwd = 'gjzsm_1987';
    public $urlPreLogin  = 'http://login.sina.com.cn/sso/prelogin.php?user=%s&entry=sso&_t=1&callback=STK_%s&rsakt=mod';
    public $urlPreLogin2 = 'http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=%s&client=ssologin.js(v1.4.2)';
    public $urlLogin = 'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.2)';
    public $urlLoginJump = '';
    public $urlAjaxLogin = 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack';
    public $urlHome = 'http://www.weibo.com/';
    public $urlComment = 'http://www.weibo.com/comment/inbox';
    public $urlFollow = 'http://www.weibo.com/%s/follow';
    
    public $followpage=0;
    public $follow=array();
    
    public $comentMsg = '在干什么呢?';
    
    public $time = '';
    public $loginStatus = 0;
    
    public $userinfo = array();
    public function login() {
        $this->time = $this->getJStime();
        $preurl = sprintf ( $this->urlPreLogin, $this->user , $this->time );
        $str = $this->curlRequest ( $preurl );
        $res = preg_match('/STK_'.$this->time.'\((.*)\)/', $str,$repArr);
        $jsonArr = json_decode($repArr[1],true);
        
        if ($jsonArr) {
            $loginData = array(
                'entry'=>'weibo',
				'gateway'=>'1',
				'from'=>'',
                'savestate'=>'7',
                'useticket'=>'1',
                'vsnf'=>'1',
                'ssosimplelogin'=>'1',
                'su'=>base64_encode(urlencode($this->user)),
                'service'=>'miniblog',
                'servertime'=>$jsonArr ['servertime'],
                'nonce'=> $jsonArr ['nonce'],
                'pwencode'=>'rsa2',
                'rsakv'=>$jsonArr['rsakv'],
                'sp'=>$this->encodePassword($jsonArr['pubkey'], $this->pwd, $jsonArr['servertime'], $jsonArr['nonce']),
                'encoding'=>'UTF-8',
                'prelt'=> max($this->getJStime() - $this->time, 100),
                'url'=>$this->urlAjaxLogin,
                'returntype'=>'META'
            );
            $str = $this->curlRequest($this->urlLogin,$loginData);   
            preg_match ( '/location\.replace\((.*)\)/', $str, $loginResultArr );
            $this->urlLoginJump = str_replace('"','',$loginResultArr[1]);            
            $str = $this->curlRequest($this->urlLoginJump);
            preg_match ( '/feedBackUrlCallBack\((.*?)\)/', $str, $loginResultArr );
            $res = json_decode($loginResultArr[1] ,true);
            if ($res['result']){
                $this->userinfo = $res['userinfo'];
                $this->loginStatus=1;
                $this->suc('login sucess');
               
            }else {
                $this->err('login faild');;
            }
        
        }else {
            $this->err('get login parm faild！');;
        }
    }
    public function login2() {
        $preLoginData = $this->curlRequest ( sprintf($this->urlPreLogin2,base64_encode ( $this->user )) );
        preg_match ( '/sinaSSOController.preloginCallBack\((.*)\)/', $preLoginData, $preArr );
        $jsonArr = json_decode ( $preArr [1], true );
        if (is_array ( $jsonArr )) {
            $postArr = array (
            'entry' => 'weibo',
            'gateway' => 1, 
            'from' => '', 
            'savestate' => 7, 
            'useticket' => 1, 
            'ssosimplelogin' => 1,
            'su' => base64_encode ( urlencode ( $this->user ) ), 
            'service' => 'miniblog',
            'servertime' => $jsonArr ['servertime'], 
            'nonce' => $jsonArr ['nonce'], 
            'pwencode' => 'wsse', 
            'sp' => sha1 ( sha1 ( sha1 ( $this->pwd ) ) . $jsonArr ['servertime'] . $jsonArr ['nonce'] ), 
            'encoding' => 'UTF-8', 
            'url' => $this->urlAjaxLogin, 
            'returntype' => 'META' );
            $loginData = $this->curlRequest ( $this->urlLogin, $postArr );
            if ($loginData) {
                $matchs = array ();
                preg_match ( '/replace\(\'(.*?)\'\)/', $loginData, $matchs );
                $this->urlLoginJump = $matchs [1];
                $loginResult = $this->curlRequest ( $this->urlLoginJump, '' );
                $loginResultArr = array ();
                preg_match ( '/feedBackUrlCallBack\((.*?)\)/', $loginResult, $loginResultArr );
                $res = json_decode($loginResultArr[1] ,true);
                if ($res['result']){
                    $this->userinfo = $res['userinfo'];
                    $this->loginStatus=1;                    
                    $this->suc('login sucess');
                    
                }else {
                    $this->err('login faild');;
                }
            } else {
                $this->err( 'Login sina fail.' );
            }
        } else {
            $this->err ( $preLoginData );
        }
       
    }
    public function getJStime(){
        return time() * 1000 + rand(0, 999);
    }
    public function encodePassword($pub_key,$servertime,$nonce,$password){
        $response   = `/usr/local/node.js-0.8.8/bin/node sso.js "$pub_key" "$servertime" "$nonce" "$password"`; 
        return substr($response, 0, strlen($response) - 1);  
    }
    /**
     * 
     * 获取我的评论
     */
    public function getComment(){
        if ($this->loginStatus){ 
            $str = $this->curlRequest($this->urlComment);
            preg_match('/domain.*.\=.*\;/', $str,$match);
            $str = $match[0];
            if ($str){
                $u = trim(str_replace(array("';","'",'='),'',strstr($str, '=')));
                $this->userinfo['domain']=$u;
            }
            
        }
    }
    /**
     * 
     * 进入我的广场首页
     */    
    public function getHome(){
        if ($this->loginStatus){
            print_r($this->userinfo);    
            if (! key_exists('domain', $this->userinfo)){
                $this->getComment();
            }       
            $url = $this->urlHome.$this->userinfo['domain'].$this->userinfo['userdomain'];
            $str = $this->curlRequest($url);
            
            
        }
    }
    /**
     * 
     * 获取用户关注列表
     * @param unknown_type $uid
     */
    public function getFollow($uid=null){
        //print_r($this->userinfo);
        if (!$uid) $uid = $this->userinfo['uniqueid'];
        $this->followpage++;
        $str = $this->curlRequest(sprintf($this->urlFollow.'?t=1&page='.$this->followpage,$uid));
        $str = str_replace(array('\t','\n',"\n","\r"), '', $str);
        //echo $str;
        $match = explode('class=\"name mbspace\">', $str);
        $a=0;
        foreach ($match as $k=>$v){
            if ($k==0) continue;
            $a++;
            $n1=str_replace('href=\"\/','',strstr($v,'href=\"\/'));
            $n2 = str_replace('\/','/',substr($n1,0,50));           
            $n3 = strstr($n2,'\\');
            $name=str_replace($n3,'',$n2);
            
            $n1=str_replace('usercard=\"id','',strstr($v,'usercard=\"id'));
            $n2 = str_replace('\/','/',substr($n1,0,50));           
            $n3 = strstr($n2,'\\');
            $id=str_replace(array($n3,'='),'',$n2);
            $arr = array('name'=>$name,'id'=>$id);
            foreach ($this->follow as $kk=>$vv){
                if ($vv['id']==$id){
                    $a=0;
                    break 2;
                }
            }
            $this->follow[]=$arr;                
        }
        if ($a){
            $this->getFollow();
        }
        //print_r($this->follow);
    }
    /**
     * 评论我关注的人的微博
     * id= 用户id
     * @param unknown_type $id
     */
    public function comentFollow($userhome=NULL,$msg=NULL,$num=1){
        $num = $num-1;
        if (!$msg) $msg = $this->comentMsg;        
        if (!$userhome){
            foreach ($this->follow as $k=>$v){
                $comentid = $this->getcontentId($v['name']);
                $this->postComent($url = $this->urlHome.$v['name'],$comentid[$num], $msg);
                die();
            }
        }else {
            $comentid = $this->getcontentId($userhome);
            //print_r($comentid);die();
            $this->postComent($url = $this->urlHome.$userhome,$comentid[$num], $msg);
        }
    }
    /**
     * 
     * 获取用户首页评论id
     * @param unknown_type $userhome
     */
    private function getcontentId($userhome){
        $url = $this->urlHome.$userhome;
        $str = $this->curlRequest($url);
        preg_match_all('/pageletM\.view\((.*)\)/', $str,$match);
        foreach ($match[1] as $k=>$v){    
            if (preg_match('/hisFeed/', $v)){
                $arr = json_decode($v,true);
                $html =$arr['html'];
                preg_match_all('/mid="(.*)\" class=/', $html,$ma);
                foreach ($ma[1] as $v){
                    $comentid[]=trim(preg_replace('/"(.*)/','',$v));
                }
                break;
            }
        }
        //print_r($comentid);die();
        return $comentid;
    }
    /**
     * 
     * 提交评论
     * @param unknown_type $mid
     * @param unknown_type $msg
     */
    public function postComent($homeurl,$mid,$msg){
        sleep(1);          
        $url = 'http://weibo.com/aj/comment/add?__rnd='.$this->getJStime();
        $postdata = array(
        'act'=>'post',
        'mid'=>$mid,
        'uid'=>$this->userinfo['uniqueid'],
        'forward'=>0,
        'isroot'=>0,
        'content'=>$msg,
        'location'=>'profile',
        'module'=>'scommlist',
        'group_source'=>'',
        '_t'=>0,
        'ajax'=>1,
        'Referer'=>$homeurl
        );
        print_r($postdata);
        $rs = json_decode($this->curlRequest($url,$postdata),true);
        if ($rs['code']=='100000'){
            return true;
        }else {
            $this->err($rs['msg'],2);
        }
        print_r($rs);
    }
    public function err($msg,$level=1){
        if ($level==1){
            echo $msg;die();
        }
        if ($level==2){
            echo $msg;;
        }
    }
    public function suc($msg){
        echo $msg."\n";
        //sleep(1);
    }
    public function curlRequest($url, $postdata = '', $cookieFile = 'mycookiefile.txt') {
        echo $url."\n";
        $ch = curl_init ();
        $option = array (CURLOPT_URL => $url, CURLOPT_HEADER => 0, CURLOPT_RETURNTRANSFER => 1 );
        
        if ($cookieFile) {
            $option [CURLOPT_COOKIEJAR] = $cookieFile;
            $option [CURLOPT_COOKIEFILE] = $cookieFile;
        }
        if ($postdata) {
            if ($postdata['ajax']){
                $option[CURLOPT_HTTPHEADER]=array(               
                'X-Requested-With: XMLHttpRequest',
                'Referer: '.$postdata['Referer'] 
                );
                unset($postdata['Referer']);
                unset($postdata['ajax']);
            }
            $option [CURLOPT_POST] = 1;
            $option [CURLOPT_POSTFIELDS] = $postdata;
            
        }        
        
        
        curl_setopt_array ( $ch, $option );
        $response = curl_exec ( $ch );
        curl_close ( $ch );
        //echo $response;
        return $response;
    }
}

?>